package com.service.impl;

import com.dao.MemberDao;
import com.dto.DTO;
import com.dto.MessageEnum;
import com.entity.Member;
import com.exception.CustomException;
import com.service.MemberService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.Random;

@Service("MemberService")
public class MemberServiceImpl implements MemberService {
    @Resource
    MemberDao memberDao;


    @Override
    public DTO<Member> getAllMembers() throws Exception {
        List<Member> members = memberDao.getAllMembers();
        MessageEnum messageEnum  = Optional.ofNullable(members).isPresent()?MessageEnum.GETALLMEMBERTUCCESS:MessageEnum.GETALLMEMBERFAIL;
        return new DTO<Member>(messageEnum.getCode(),messageEnum.getMessage(),members);
    }

    @Transactional(rollbackFor = CustomException.class)
    @Override
    public DTO<Member> updateMememberTest(Member member) throws CustomException{
        Member member1 = new Member();
        member1.setMno(member.getMno());
        member1.setMname(member.getMname());
        Integer result = memberDao.updateMember(member1);
        if(Math.abs(new Random().nextInt()) % 2 == 0){
            throw new CustomException("选课失败");}
        Member member2 = new Member();
        member2.setMno(member.getMno());
        member2.setMpwd(member.getMpwd());
             result = memberDao.updateMememberTest(member2);
        //isPresent表示判断不为空成立则dto为？与：之间的对象
        MessageEnum messageEnum  =result> 0?MessageEnum.GETALLMEMBERTUCCESS:MessageEnum.GETALLMEMBERFAIL;
        return new DTO<Member>(messageEnum.getCode(),messageEnum.getMessage());
    }

    @Override
    public DTO<Member> addMember(Member member) {
        Integer result = memberDao.addMember(member);
        //isPresent表示判断不为空成立则dto为？与：之间的对象
        MessageEnum messageEnum  =result> 0?MessageEnum.GETMEMBERTYPESUCCESS:MessageEnum.GETALLMEMBERFAIL;
        return new DTO<Member>(messageEnum.getCode(),messageEnum.getMessage());
    }


    @Override
    public DTO<Member> updateMember(Member member) {
        Integer result = memberDao.updateMember(member );
        //isPresent表示判断不为空成立则dto为？与：之间的对象
        MessageEnum messageEnum  =result> 0?MessageEnum.GETMEMBERTYPESUCCESS:MessageEnum.GETALLMEMBERFAIL;
        return new DTO<Member>(messageEnum.getCode(),messageEnum.getMessage());
    }
    @Override
    public DTO<Member> deleteMemberById(Integer aId) {
        Integer result = memberDao.deleteMemberById( aId );
        //isPresent表示判断不为空成立则dto为？与：之间的对象
        MessageEnum messageEnum  =result> 0?MessageEnum.GETMEMBERTYPESUCCESS:MessageEnum.GETALLMEMBERFAIL;
        return new DTO<Member>(messageEnum.getCode(),messageEnum.getMessage());
    }

}
